﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.IO;
namespace JobSeek.Classes
{
    public class AdvertiserMembershipProvider : ParentMembershipProvider
    {
        public static bool CheckAdvertiser(string username)
        {
            using (job_seekerEntities ctx = new job_seekerEntities())
            {
                var result = ctx.Advertisers.SingleOrDefault(ad => ad.username == username);

                if (result != null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

        /// <summary>
        /// Validate Advertiser upon logging in
        /// </summary>
        /// <param name="username">username of employers when they register</param>
        /// <param name="password">password</param>
        /// <returns>true if Advertiser is found</returns>
        public bool ValidateAdvertiser(string username, string password)
        {
            bool success = false;
            //get salt from the database
            using (job_seekerEntities ctx = new job_seekerEntities())
            {
                Advertiser Advertiser = (from emp in ctx.Advertisers
                                         where emp.username == username
                                         select emp).SingleOrDefault<Advertiser>();

                if (Advertiser != null)
                {
                    string salt = Advertiser.salt;

                    string hashSaltAndPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(salt + password, "SHA1");

                    if (Advertiser.password == hashSaltAndPassword)
                    {
                        success = true;
                    }
                    else
                    {
                        //incrememt pwd attempt by 1. If pwd attempt reaches 5, user account will be lock until futher notice.
                        Advertiser.pwd_attempts += 1;

                        if (Advertiser.pwd_attempts == 5)
                        {
                            //will be unable to login
                            Advertiser.account_disabled = true;
                        }
                        success = false;
                    }

                }
            }

            return success;

        }


        public bool SetAdvertiserInactive(string username)
        {
            //if account expire, set to inactive
            try
            {
                using (job_seekerEntities ctx = new job_seekerEntities())
                {
                    Advertiser advertiser = (from emp in ctx.Advertisers
                                             where emp.username == username
                                             select emp).SingleOrDefault<Advertiser>();
                    if (advertiser != null)
                    {
                        advertiser.account_disabled = true;

                        ctx.SaveChanges();
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                //Log error here!
                return false;
            }
        }
        
        public static bool CreateAdvertiser(Advertiser advertiser)
        {
            string salt = CreateSalt(new Random().Next(1, 100));
            string hashedPwd = CreateHashPassword(advertiser.password, salt);
            advertiser.password = hashedPwd;
            advertiser.salt = salt;

            advertiser.pwd_attempts = 0;
            advertiser.account_disabled = false;

            using (job_seekerEntities ctx = new job_seekerEntities())
            {
                ctx.AddToAdvertisers(advertiser);
                try
                {
                    ctx.SaveChanges();

                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

        }

        /// <summary>
        /// Reset password for Advertiser
        /// </summary>
        /// <param name="email">email when they registered</param>
        /// <returns>true if the password is successfully reset</returns>
        public bool ResetPasswordForAdvertiser(string email)
        {
            bool success = false;
            //send pwd to user.
            //generate a alphanumeric pwd to user and ask them to change on login
            string randPassword = GenerateRandPassword();
            string salt = CreateSalt(new Random().Next(1, 100));
            using (job_seekerEntities ctx = new job_seekerEntities())
            {

                Advertiser advertiser = (from emp in ctx.Advertisers
                                         where emp.email == email
                                         select emp).SingleOrDefault<Advertiser>();

                if (advertiser != null)
                {
                    string hashPwd = CreateHashPassword(randPassword, salt);

                    advertiser.password = hashPwd;

                    try
                    {
                        ctx.SaveChanges();
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        success = false;
                    }
                    //send email to them telling them that thier password has change.
                }

                if (success)
                {
                    string body = new StreamReader(HttpContext.Current.Server.MapPath("~/Email_Template/reset_pwd.htm")).ReadToEnd().Replace("%Message%", randPassword);
                    //string body = "Your password has been reset. Please login with this new password and change it immediately after login.";
                    string subject = "Password Resetted";

                    //might give error if smtp server has error. Catch the exception in SendEmail()
                    SendEmail(body, subject, advertiser.email);
                }
            }
            return success;

        }

    }
}